package com.xyy.saas.payment.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class ZipUtils {
    private static final Logger log = LoggerFactory.getLogger(ZipUtils.class);
          
    private ZipUtils(){};  
   /** 
     * 创建ZIP文件 
     * @param sourcePath 文件或文件夹路径 
     * @param zipPath 生成的zip文件存在路径（包括文件名） 
     */  
    public static void createZip(String sourcePath, String zipPath) {  
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        try {  
            fos = new FileOutputStream(zipPath);
            zos = new ZipOutputStream(fos);  
            writeZip(new File(sourcePath), "", zos);
        } catch (Exception e) {
            log.error("创建ZIP文件失败",e);  
        } finally {  
            try {  
                if (zos != null) {  
                    zos.close();  
                }  
            } catch (IOException e) {
                log.error("创建ZIP文件失败",e);  
            }  
  
        }  
    }  
      
    private static void writeZip(File file, String parentPath, ZipOutputStream zos) {  
        if(file.exists()){  
            //处理文件夹  
            if(file.isDirectory()){  
                parentPath+=file.getName()+File.separator;  
                File [] files=file.listFiles();  
                for(File f:files){  
                    writeZip(f, parentPath, zos);  
                }  
            }else{  
                FileInputStream fis=null;  
                DataInputStream dis=null;  
                try {  
                    fis=new FileInputStream(file);
                    dis=new DataInputStream(new BufferedInputStream(fis));
                    ZipEntry ze = new ZipEntry(parentPath + file.getName());
                    zos.putNextEntry(ze);
                    byte [] content=new byte[1024];  
                    int len;  
                    while((len=fis.read(content))!=-1){  
                        zos.write(content,0,len);  
                        zos.flush();  
                    }  
                } catch (FileNotFoundException e) {  
                    log.error("创建ZIP文件失败",e);  
                } catch (IOException e) {  
                    log.error("创建ZIP文件失败",e);  
                }finally{  
                    try {  
                        if(dis!=null){  
                            dis.close();  
                        }  
                    }catch(IOException e){  
                        log.error("创建ZIP文件失败",e);  
                    }  
                }  
            }  
        }  
    }

    /**
     * zip解压
     * @param srcZipFile      zip源文件
     * @param destDirPath     解压后的目标文件夹
     * @throws RuntimeException 解压失败会抛出运行时异常
     */
    public static void unZip(String srcZipFile, String destDirPath) throws Exception {
        long start = System.currentTimeMillis();
        File srcFile = new File(srcZipFile);
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
        }
        // 开始解压
        ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(srcFile);
            Enumeration<?> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                log.info("解压文件:{}", entry.getName());
                // 如果是文件夹，就创建个文件夹
                if (entry.isDirectory()) {
                    String dirPath = destDirPath + "/" + entry.getName();
                    File dir = new File(dirPath);
                    dir.mkdirs();
                } else {
                    InputStream is = null;
                    FileOutputStream fos = null;
                    try {
                        // 如果是文件，就先创建一个文件，然后用io流把内容copy过去
                        File targetFile = new File(destDirPath + "/" + entry.getName());
                        // 保证这个文件的父文件夹必须要存在
                        if (!targetFile.getParentFile().exists()) {
                            targetFile.getParentFile().mkdirs();
                        }
                        targetFile.createNewFile();
                        // 将压缩文件内容写入到这个文件中
                        is = zipFile.getInputStream(entry);
                        fos = new FileOutputStream(targetFile);
                        int len;
                        byte[] buf = new byte[1024];
                        while ((len = is.read(buf)) != -1) {
                            fos.write(buf, 0, len);
                        }
                    } catch (Exception e) {
                        throw e;
                    } finally {
                        // 关流顺序，先打开的后关闭
                        if (null != fos) {
                            fos.close();
                        }
                        if (null != is) {
                            is.close();
                        }
                    }
                }
            }
            log.info("解压[{}]完成，耗时: {}ms", srcZipFile, System.currentTimeMillis() - start);
        } catch (Exception e) {
            log.error("unzip error from ZipUtils {}", e);
            throw new Exception("unzip error from ZipUtils", e);
        } finally {
            if(zipFile != null){
                try {
                    zipFile.close();
                } catch (IOException e) {
                    log.error("{}", e);
                }
            }
        }
    }

    public static void main(String[] args) {  
        //测试把F盘下的所有文件打包压缩成sql.zip文件放在F盘根目录下  
        ZipUtils.createZip("F:/", "F:/sql.zip");  
          
    }  
}  